<script setup>
import {ref } from "vue"
import BaseNode from './BaseNode.vue';
import AI from './ai';
import Markdown from 'vue3-markdown-it';
const props = defineProps(["id"])

const background = ref("");
const prompt = ref("")
const answer = ref("");
const think = ref("");
const loading = ref(false)
const ai = new AI("/v1/chat/completions","DeepSeek-R1-Distill-Qwen-32B");
ai.use_default_params();
const toggle = ()=>{
    // console.log("json:",background.value)
    let thinking  = false;
    let data = background.value;
    if (Array.isArray(data)){
        data = JSON.stringify(data);
    }
    let q = `## 加载的内容：
${data}
## 问题： ${prompt.value}`;
    loading.value = true
    ai.stream(q,(data)=>{
        let msg = data.choices[0].delta.content;
        if (msg.match(/<think>/g)){
            msg = msg.replace(/<think>/g, '');
            thinking = true;
        }else if (msg.match(/<\/think>/g)){
            msg = msg.replace(/<\/think>/g, '');
            thinking = false;
        }
        if (thinking){

            think.value += msg;
        }else{
            loading.value = false
            answer.value += msg
            prompt.value = ""
        }
    })
}
</script>

<template>
    <BaseNode :loading="loading" :id="props.id" v-model:sourceData="background" source extend >
        <template #extend>
            <n-gradient-text type="info" :size=12 :gradient="{from: '#70c0e8',to: '#63e2b7'}" >
                <pre style="text-wrap: auto;word-break: break-all;">{{ think.trim()}}</pre>
            </n-gradient-text>
            <Markdown :source="answer"></Markdown>
        </template>
        <n-collapse :default-expanded-names="['show']">
            <n-collapse-item name="background" tab="背景">
                <template #header>
                    <n-gradient-text type="primary" :size=12 :gradient="{from: '#70c0e8',to: '#63e2b7'}" >背景:{{ background.length }}</n-gradient-text>
                </template>
                <pre >背景：{{ background }}</pre>
            </n-collapse-item>
        </n-collapse>
        <n-input-group>
            <n-input  v-model:value="prompt" @keyup.enter="toggle" ></n-input>
            <n-button @click="toggle">AI</n-button>    
        </n-input-group>    
        
    </BaseNode>

</template>